package comp.wxapi.service;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.TypedQuery;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import comp.wxapi.entity.AccessToken;
import comp.wxapi.repository.AccessTokenRepository;
import weixin.popular.api.API.APIHandler;
import weixin.popular.api.TokenAPI;
import weixin.popular.bean.token.Token;

@Service
public class APIService implements APIHandler {

	@Autowired
	AccessTokenRepository accessTokenRepo;
	@PersistenceUnit
	EntityManagerFactory emf;

	/**
	 * 公众号授权模式下，获取微信接口调用凭证access_token
	 */
	@Override
	public String accessToken(String component_appid, String authorizer_appid) {
		// TODO
		return null;
	}

	/**
	 * 非公众号授权模式下，获取微信公众号接口调用凭证access_token
	 */
	@Override
	public String accessToken(String appid) {
		EntityManager em = null;
		String appsecret = WxAbstractBaseService.APPID_SECRET_CONFIG.get(appid);
		try {
			AccessToken accessToken = null;
			em = emf.createEntityManager();
			List<AccessToken> list = null;
			String hql = "from AccessToken e where e.appid=:appid";
			TypedQuery<AccessToken> query = em.createQuery(hql, AccessToken.class);
			query.setParameter("appid", appid);
			list = query.getResultList();
			if (list != null && !list.isEmpty()) {
				long now = new Date().getTime() / 1000;
				accessToken = list.get(0);
				long createTime = accessToken.getCreate_time();
				long expires_in = accessToken.getExpires_in();
				if (now - createTime > expires_in - 200) {// token过期
					Token token = TokenAPI.token(appid, appsecret);
					if (token != null && token.isSuccess()) {
						accessToken.setAccess_token(token.getAccess_token());
						accessToken.setAppid(appid);
						accessToken.setCreate_time(new Date().getTime() / 1000);
						accessToken.setExpires_in(Long.parseLong(String.valueOf(token.getExpires_in())));
						accessTokenRepo.save(accessToken);
						return token.getAccess_token();
					}
				} else {// token没过期

					return accessToken.getAccess_token();
				}
			} else {
				accessToken = new AccessToken();
				Token token = TokenAPI.token(appid, appsecret);
				if (token != null && token.isSuccess()) {
					accessToken.setAccess_token(token.getAccess_token());
					accessToken.setAppid(appid);
					accessToken.setCreate_time(new Date().getTime() / 1000);
					accessToken.setExpires_in(Long.parseLong(String.valueOf(token.getExpires_in())));
					accessTokenRepo.save(accessToken);
					return token.getAccess_token();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (em != null) {
				em.close();
			}
			WxAbstractBaseService.APPID_SECRET_CONFIG.remove(appid);
		}
		return null;
	}

	@Override
	public String componentAccessToken(String component_appid) {
		// TODO
		return null;
	}

	@Override
	public String ticket(String component_appid, String authorizer_appid, String type) {
		// TODO
		return null;
	}

	@Override
	public String ticket(String appid, String type) {
		// TODO
		return null;
	}

}